<?php
namespace module\app\controller;

use app\Controller;
use app\model\User as Model;
use app\model\UserThird;
use app\model\UserFocus;
use app\model\UserNotice;
use app\helper\Ident;

class Visitor extends Controller
{
    /**
     * 密码登录.
     * 
     */
    public function login()
    {
        $post = input('post.');
        $model = Model::where('mobile', $post['mobile'])->withTrashed()->findOrEmpty();

        if (!$model->isEmpty() && $model->status !== 2) {
            return ['code' => 0, 'msg' => '账号异常!'];
        }

        $model->save(['status' => 2, 'delete_at' => 0] + $post);

        $wechat = UserThird::where([['user_id', '=', $model->id], ['type', '=', 1]])->findOrEmpty();
        $wechat->save(['user_id' => $model->id, 'openid' => $post['openid'], 'type' => 1]);

        $data = ['token' => Ident::token(['uid' => $model->id, 'mobile' => $model->mobile, 'openid' => $post['openid']]), 'id' => $model->id]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['token'], $data + ['openid' => $model->openid, 'mobile' => $model->mobile, 'login_at' => time()]);

        return json($data + [
            'is_auth' => !empty($model->mobile),
            'nickname' => $post['nickname'] ?? '用户' . $model->id,
            'avatar' => $post['avatar'] ?? '',
            'focusCount' => UserFocus::scope('user')->count(),
            'fansCount' => UserFocus::scope('aim')->count(),
            'noticeCount' => UserNotice::scope('user')->count(),
        ]);
    }
    /**
     * 注册.
     * 
     */
    public function signup()
    {    
        $model = new Model;
        $model->save(input('post.'));
        return json([
            'access_token' => Ident::token(['id' => $model->id, 'mobile' => input('post.mobile/s')])
        ]);
    }
    /**
     * 重置密码.
     * 
     */
    public function forget()
    {
        // 获取token
        $model = Model::where('mobile', input('post.mobile/s'))->findOrFail();
        $model->password = md5(input('post.password/s'));
        $model->save();
        $data = ['access_token' => Ident::token(['id' => $model->id, 'mobild' => input('post.mobile/s')]), 'id' => $model->id]; //参数为用户认证的信息，请自行添加
        redis()->hset('UserAccessTokenList', $data['access_token'], $data + ['login_at' => time()]);
        return json($data);
    }
}
